package xhg.com.resell.base.httpbase;


import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import xhg.com.resell.R;
import xhg.com.resell.utils.CommonUtils;

/**
 *
 * @author lew1210
 * @date 2017/7/11
 * 自定义Gson 响应体变换器
 */

public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private Gson gson;
    private Type type;

    public GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        Result result = null;
        try {
            result = gson.fromJson(response, Result.class);
            if (result == null) {
                throw new ApiException(CustomException.UNKNOWN, CommonUtils.getString(R.string.unknown_error));
            }
            if (result.getStatus() == -1) {
                throw new ApiException(CustomException.NETWORK_ERROR, CommonUtils.getString(R.string.unconnected_error));
            }
            if (result.isSuccess()) {
                return gson.fromJson(response, type);
            } else {
                throw new ApiException(result.getStatus(), result.getMsg());
            }
        } catch (Exception e) {
            throw CustomException.handleException(e);
        } finally {
            value.close();
        }

    }
}
